﻿using HalconDotNet;
using Halcon二次开发.Controller.CamerForm交互;
using Halcon二次开发.Controller.Controller基类;
using Halcon二次开发.Controller.主界面交互;
using Halcon二次开发.Model.储存每个Controller的单例对象;
using Halcon二次开发.Model.储放所有单例.储存每个单例界面;
using Halcon二次开发.Model.图像绑定流程图显示;
using Halcon二次开发.View.相机;
using Halcon二次开发.View.统计图;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Halcon二次开发.Model.自定义控件
{
    public partial class HwindowFlowNodeUrseControl : UserControl
    {
        /// <summary>
        /// 这个板块的所有小窗体
        /// </summary>
        public List<Form> forms = new List<Form>();
        //控件的名字
        public string name;
        /// <summary>
        /// 当前显示的图像(需要一直获取)
        /// </summary>
        public HImage hImage;

        public Form1Controller form1Controller;
        /// <summary>
        /// 图像索引
        /// </summary>
        public int count;

        /// <summary>
        /// 鼠标右击选择输入输出的子节点对象
        /// </summary>
        public TreeNode mouseNode;
        /// <summary>
        /// 鼠标出现在节点上方获取的节点对象
        /// </summary>
        public TreeNode msMoveNode;
        //统计图窗体对象
        private StatisticsForm statisticsForm;
        public HwindowFlowNodeUrseControl()
        {
            InitializeComponent();
            //取消线程之间的访问
            CheckForIllegalCrossThreadCalls=false;
            //给HSmart绑定缩放事件
            hSmartWindowControl1.MouseWheel += HSmartWindowControl1_MouseWheel;
            foreach (Image item in ((Form1)FormDb.Db["Form1"]).imageList1.Images)
            {
                imageList1.Images.Add(item);
            }
            treeView1.SelectedImageIndex = 149;
            statisticsForm=new StatisticsForm();
        }

        private void HSmartWindowControl1_MouseWheel(object sender, MouseEventArgs e)
        {
            hSmartWindowControl1.HSmartWindowControl_MouseWheel(sender, e);
        }

        /// <summary>
        /// 开始拖拽
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            DoDragDrop(e.Item, DragDropEffects.Move);
        }
        /// <summary>
        /// 拖入工作区   
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }
        /// <summary>
        /// 拖放完成时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            //终点节点坐标
            Point dropPoint = treeView1.PointToClient(new Point(e.X, e.Y));
            //终点节点
            TreeNode targetNode = treeView1.GetNodeAt(dropPoint);

            if (targetNode == null)
            {
                // 拖拽到TreeView的空白区域，可以根据需要处理  
                return;
            }
            //当前节点
            TreeNode draggedNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
            //
            if (draggedNode.Parent!= null)
            {
                return;
            }
            // 防止节点移动到其子节点或自己内部  
            if (draggedNode.Parent == targetNode)
            {
                return;
            }

            //判断头部
            if (targetNode.Index == 0 && targetNode.Parent == null)
            {
                draggedNode.Remove();
                treeView1.Nodes.Insert(0, draggedNode);
                //末尾节点
            }
            else if (targetNode.Index == treeView1.Nodes.Count - 1 && targetNode.Parent == null)
            {
                draggedNode.Remove();
                treeView1.Nodes.Add(draggedNode);
            }
            else
            {
                // 移动节点  
                if (targetNode.Parent == null && draggedNode.Parent == null)
                {
                    int index = treeView1.Nodes.IndexOf(targetNode);
                    // 拖拽到根节点  
                    draggedNode.Remove();
                    treeView1.Nodes.Insert(index, draggedNode);
                }
                else
                {
                    //判断是不是子节点,必须要两个节点都没有父节点
                    if (draggedNode.Parent != null && targetNode.Parent != null)
                    {
                        Graphics gh = treeView1.CreateGraphics();
                        Pen pen = new Pen(Color.Red);

                        gh.DrawLine(pen, dropPoint, new Point(200));
                    }
                    return;
                }
            }
            // 可选：确保拖动的节点是可见的  
            treeView1.SelectedNode = draggedNode;
            if (targetNode != null)
            {
                DisconnectLink(targetNode);
            }
            if (draggedNode != null)
            {
                DisconnectLink(draggedNode);
            }
        }
        /// <summary>
        /// 拖放完成后 断开不正确的连接
        /// </summary>
        private void DisconnectLink(TreeNode node)
        {
            int index = treeView1.Nodes.IndexOf(node);
            TreeNodeCollection childNodes = node.Nodes;
            foreach (TreeNode childNode in childNodes)
            {
                if (!childNode.Text.Contains("<—")) continue;
                string[] values = childNode.Text.Split(new char[] { '—', '<', '.' }, StringSplitOptions.RemoveEmptyEntries);
                bool paper = true;
                for (int i = 0; i < index; i++)
                {
                    if (treeView1.Nodes[i].Text == values[1])
                    {
                        paper = false;
                    }
                }
                if (paper)
                {
                    childNode.Text = childNode.Name;
                    childNode.ForeColor = Color.Black;
                }
            }
        }
        /// <summary>
        /// 双击打开页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            form1Controller.ShowForm(e.Node.Tag);
        }

        /// <summary>
        /// 运行(下一张图片)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void toolStripButton1_Click(object sender, EventArgs e)
        {
            foreach (TreeNode item in treeView1.Nodes)
            {
                FieldInfo controller = item.Tag.GetType().GetField("controller");
                if (controller == null) continue;
                object sss = controller.GetValue(item.Tag).GetType().GetMethod("Run");
                MethodInfo run = controller.GetValue(item.Tag).GetType().GetMethod("Run");
                if (run == null) continue;


                //更新图像到本句柄中(要本相机类型的)
                if (controller.GetValue(item.Tag).GetType() == typeof(CamerFormController))
                {
                    try
                    {
                        run.Invoke(controller.GetValue(item.Tag), null);

                        FieldInfo field = controller.GetValue(item.Tag).GetType().GetField("OutputImage");
                        HImage outputImage = (HImage)field.GetValue(controller.GetValue(item.Tag));
                        if (outputImage == null) continue;
                        hSmartWindowControl1.HalconWindow.DispObj(outputImage);
                        //图像居中
                        hSmartWindowControl1.SetFullImagePart();
                        item.ForeColor = Color.Black;
                    }
                    catch (Exception ex)
                    {
                       string noweDate= DateTime.Now.ToString("MM:dd:HH:mm:ss");
                        (FormDb.Db["Form1"] as Form1).textBox1.AppendText(item.Name + ":" + ex.InnerException.Message +"  "+ noweDate+"\r\n");
                        item.ForeColor = Color.Red;
                    }
                }
                //不是相机工具
                else
                {
                    try
                    {
                        //给连接的子节点赋值(要给每个动作类中的Himage更新)
                        foreach (TreeNode child in item.Nodes)
                        {
                            //当前节点文本
                            if (child.Text.Contains("<—"))
                            {
                                string str = child.Text.Substring(child.Text.IndexOf('—') + 1);
                                //起点值
                                string StartValue = child.Text.Substring(0, child.Text.IndexOf('<'));
                                //终点工具
                                string EndTool = str.Substring(0, str.IndexOf('.'));
                                //终点值
                                string EndValue = str.Substring(str.IndexOf('.') + 1);

                                TreeNode EndTreeNode = null;

                                //用反射出来的值
                                foreach (TreeNode item2 in treeView1.Nodes)
                                {
                                    if (item2.Text == EndTool)
                                    {
                                        EndTreeNode = item2;
                                    }
                                }
                                if (EndTreeNode != null)
                                {
                                    object value = EndTreeNode.Tag.GetType().GetField("controller").GetValue(EndTreeNode.Tag).GetType().GetField(EndValue).GetValue(EndTreeNode.Tag.GetType().GetField("controller").GetValue(EndTreeNode.Tag));
                                    // 对连接后的数据进行更新
                                    child.Tag.GetType().GetField(StartValue).SetValue(child.Tag, value);
                                }
                            }
                        }
                        run.Invoke(controller.GetValue(item.Tag), null);
                        item.ForeColor = Color.Black;

                       
                    }
                    catch (Exception ex)
                    {
                        string noweDate = DateTime.Now.ToString("MM:dd:HH:mm:ss");
                        (FormDb.Db["Form1"] as Form1).textBox1.AppendText(item.Name + ":" + ex.InnerException.Message + "  " + noweDate + "\r\n");
                        item.ForeColor = Color.Red;
                    }
                    
                }
            }
            if (statisticsForm!=null)
            {

                statisticsForm.ClickRun(sender,e);
            }
        }

        /// <summary>
        /// 右击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                mouseNode = treeView1.GetNodeAt(e.X, e.Y);
                if (mouseNode != null && (mouseNode.Name.Contains("Int") || mouseNode.Name.Contains("Out") || mouseNode.Name.Contains("IntOrOut")))
                {
                    //获取父节点
                    TreeNode fatherNode = mouseNode.Parent;
                    //获取父亲节点在treeview的下标
                    int index = treeView1.Nodes.IndexOf(fatherNode);
                    //获取右击菜单
                    ContextMenuStrip context = mouseNode.ContextMenuStrip;
                    //排除没有右击菜单的节点
                    if (context == null) return;
                    (context.Items[0] as ToolStripMenuItem).DropDownItems.Clear();
                    //排除根节点
                    if (index == 0) return;

                    //遍历此节点父节点上面所有节点 
                    for (int i = 0; i < index; i++)
                    {
                        //查找每个根节点下的所有子节点
                        TreeNodeCollection nodes = treeView1.Nodes[i].Nodes;
                        foreach (TreeNode item in nodes)
                        {
                            if (item.Name.Contains("Out"))
                            {
                                //通过反射 获取当前遍历的节点（字段）
                                FieldInfo itemInfo = item.Tag.GetType().GetField(item.Name);
                                //通过反射 获取鼠标右击得到的节点（字段）
                                FieldInfo mInFo = mouseNode.Tag.GetType().GetField(mouseNode.Name);
                                //添加右击菜单  --这里我加了一下条件
                                if (itemInfo.FieldType.Name == mInFo.FieldType.Name)
                                {
                                    ToolStripMenuItem menuItem1 = new ToolStripMenuItem(treeView1.Nodes[i].Name + "." + item.Name);
                                    menuItem1.Tag = item.Tag;
                                    menuItem1.Click += MenuItem1_Click;
                                    (context.Items[0] as ToolStripMenuItem).DropDownItems.Add(menuItem1);
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 选择连接的输出节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem1_Click(object sender, EventArgs e)
        {
            //之后写 本数据<=外部数据
            if (mouseNode != null && mouseNode.ForeColor != Color.Green)
            {
                //先记录进来之间的节点名字
                string text = mouseNode.Text;
                mouseNode.Text = mouseNode.Text + "<—" + (sender as ToolStripMenuItem).Text;
                mouseNode.ForeColor = Color.Green;
                //在这里进行数据迭代 反射设置对应字段值
                //获取所有字段--输出的
                FieldInfo[] fieldsOut = (sender as ToolStripMenuItem).Tag.GetType().GetFields();
                //获取所有字段--输入的
                FieldInfo[] fieldsIn = mouseNode.Tag.GetType().GetFields();

                object OutValue = null;
                foreach (FieldInfo field in fieldsOut)
                {
                    if (field.Name == (sender as ToolStripMenuItem).Text.Substring((sender as ToolStripMenuItem).Text.IndexOf('.') + 1))
                    {
                        OutValue = field.GetValue((sender as ToolStripMenuItem).Tag);
                        break;
                    }
                }
                //如果没有图像层则不让连接成功
                if (OutValue == null) return;

                foreach (FieldInfo field in fieldsIn)
                {
                    if (text == field.Name)
                    {
                        field.SetValue(mouseNode.Tag, OutValue);
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// 鼠标出现在子节点上方时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_MouseMove(object sender, MouseEventArgs e)
        {
            TreeViewHitTestInfo hitTestInfo = treeView1.HitTest(e.Location);
            TreeNode node = hitTestInfo.Node;
            if (node == msMoveNode)
            {
                return;
            }
            msMoveNode = node;
            if (node != null && (node.Name.Contains("Int") || node.Name.Contains("Out")))
            {
                string str = "null";
                //获取节点绑定tag对象
                object controller = node.Tag;
                FieldInfo field = node.Tag.GetType().GetField(hitTestInfo.Node.Name);
                if (field.GetValue(controller) != null)
                {
                    str = field.GetValue(controller).ToString();
                }
                if (str == "null")
                {
                    str = field.FieldType.Name + "<Nothing>";
                }
                toolTip1.SetToolTip(treeView1, str);
                // 假设你有一个方法来获取节点的额外信息  
                toolTip1.SetToolTip(treeView1, str);
            }
            else
            {
                toolTip1.SetToolTip(treeView1, string.Empty);
            }
        }

        /// <summary>
        /// 显示原图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 原图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (TreeNode node in treeView1.Nodes) {
                if (node.Text.Contains("CamerTool"))
                {
                    CamerForm camer = node.Tag as CamerForm;
                    //显示原图
                    if (camer.controller.HideOutputImage != null)
                    {
                        hSmartWindowControl1.HalconWindow.DispObj(camer.controller.HideOutputImage);
                    }
                }
            }
        }
        //显示统计图窗体
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            statisticsForm.Show();
            statisticsForm.SetNodesUrse(StaicResouce.HwindowFlowNodeUrse,treeView1,this);
        }
    }
}
